package cn.zysheep.utils;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import lombok.extern.slf4j.Slf4j;


import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Semaphore;

@Slf4j
public class NacosWeightedRule extends AbstractLoadBalancerRule {

    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {
        //读取配置文件
    }

     @Override
     public Server choose(Object o) {
       ILoadBalancer loadBalancer = this.getLoadBalancer();
       BaseLoadBalancer baseLoadBalancer = (BaseLoadBalancer) loadBalancer;
       //获取要请求的微服务名称
       String name = baseLoadBalancer.getName();
      //获取服务发现的相关API
      NamingService namingService = nacosDiscoveryProperties.namingServiceInstance( );
      try {
          Instance instance = namingService.selectOneHealthyInstance(name);
          log.info("选择的实例是port= {},instance={}",instance.getPort(),instance);
          return new NacosServer(instance);
      } catch (NacosException e) {
          e.printStackTrace();
          return null;
      }
    }

    public static void main(String[] args) {
        //有A,B,C三个线程，如何保证三个线程同时执行
        final CountDownLatch countDownLatch = new CountDownLatch(1);
        //如何在并发情况下保证三个线程依次执行
        final CyclicBarrier cyclicBarrier = new CyclicBarrier(1);
        //如何保证三个线程有序交错进行
        final Semaphore semaphore = new Semaphore(1);

    }
}
